<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of DateTimeServer
 *
 * @author AOF
 */
class DateTimeServer {

    public static $MICROSECOND = 'MICROSECOND';
    public static $SECOND = 'SECOND';
    public static $MINUTE = 'MINUTE';
    public static $HOUR = 'HOUR';
    public static $DAY = 'DAY';
    public static $WEEK = 'WEEK';
    public static $MONTH = 'MONTH';
    public static $QUARTER = 'QUARTER';
    public static $YEAR = 'YEAR';
    public static $SECOND_MICROSECOND = 'SECOND_MICROSECOND';
    public static $MINUTE_MICROSECOND = 'MINUTE_MICROSECOND';
    public static $MINUTE_SECOND = 'MINUTE_SECOND';
    public static $HOUR_MICROSECOND = 'HOUR_MICROSECOND';
    public static $HOUR_SECOND = 'HOUR_SECOND';
    public static $HOUR_MINUTE = 'HOUR_MINUTE';
    public static $DAY_MICROSECOND = 'DAY_MICROSECOND';
    public static $DAY_SECOND = 'DAY_SECOND';
    public static $DAY_MINUTE = 'DAY_MINUTE';
    public static $DAY_HOUR = 'DAY_HOUR';
    public static $YEAR_MONTH = 'YEAR_MONTH';

    public function getNowDate($format = NULL) {
        if (isset($format)) {
            return Yii::app()->db->createCommand('SELECT DATE_FORMAT(NOW(),:FORMAT)')->queryScalar(array(':FORMAT' => $format));
        } else {
            return Yii::app()->db->createCommand('SELECT CURDATE()')->queryScalar();
        }
    }

    public function getNowTime($format = NULL) {
        if (isset($format)) {
            return Yii::app()->db->createCommand("SELECT DATE_FORMAT(NOW(),:FORMAT)")->queryScalar(array(':FORMAT' => $format));
        } else {
            return Yii::app()->db->createCommand('SELECT CURTIME()')->queryScalar();
        }
    }

    public function getNowDateTime($format = NULL) {
        if (isset($format)) {
            return Yii::app()->db->createCommand("SELECT DATE_FORMAT(NOW(),:FORMAT)")->queryScalar(array(':FORMAT' => $format));
        } else {
            return Yii::app()->db->createCommand('SELECT NOW()')->queryScalar();
        }
    }

    public function getNowDateAdd($count = 0, $type = 'DAY', $format = "%Y-%m-%d") {
        $sql = 'SELECT DATE_ADD(DATE_FORMAT(NOW(),"{0}"),INTERVAL {1} {2})';
        $sql = str_replace('{0}', $format, $sql);
        $sql = str_replace('{1}', $count, $sql);
        $sql = str_replace('{2}', $type, $sql);
        return Yii::app()->db->createCommand($sql)->queryScalar();
    }

    public function getNowDateSub($count = 0, $type = 'DAY', $format = "%Y-%m-%d") {
        $sql = 'SELECT DATE_SUB(DATE_FORMAT(NOW(),"{0}"),INTERVAL {1} {2})';
        $sql = str_replace('{0}', $format, $sql);
        $sql = str_replace('{1}', $count, $sql);
        $sql = str_replace('{2}', $type, $sql);
        return Yii::app()->db->createCommand($sql)->queryScalar();
    }

}

?>
